﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OAuth
{
    public static class OAuthCommon
    {
        /// <summary>
        /// 获取的当前时间戳整型值
        /// </summary>
        /// <returns>时间戳整型值</returns>
        public static string GetOAuthTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }

        /// <summary>
        /// 得到随机值
        /// </summary>
        /// <returns>GUID</returns>
        public static string GetOAuthNonce()
        {
            return Guid.NewGuid().ToString().Substring(0, 32);
        }

        /// <summary>
        /// 对字符串进行编码
        /// </summary>
        /// <param name="value">要编码的字符串</param>
        /// <returns>编码后的字符串</returns>
        public static string UrlEncode(string value)
        {
            StringBuilder result = new StringBuilder();
            string unreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
            foreach (char symbol in value)
            {
                if (unreservedChars.IndexOf(symbol) != -1)
                {
                    result.Append(symbol);
                }
                else
                {
                    result.Append('%' + String.Format("{0:X2}", (int)symbol));
                }
            }
            return result.ToString();
        }
    }
}
